#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <functional>
using namespace std;

namespace Server
{
    static const int gnum = 1024;
    static const string def = "0.0.0.0";
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        OPEN_ERR
    };
    class udpServer
    {
        typedef function<void(int, string, uint16_t, string)> func_t;

    public:
        udpServer(func_t cb, const uint16_t &port, const string &ip = def)
            : _port(port), _sockfd(-1), _callback(cb)
        {
        }
        void InitServer()
        {
            // 创建udp socket套接字
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                cerr << "socket error" << ":" << errno << strerror(errno) << endl;
                exit(SOCKET_ERR);
            }
            // bind套接字
            struct sockaddr_in local;
            bzero(&local, 0);
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);             // 主机序列转换为网络序列
            local.sin_addr.s_addr = htonl(INADDR_ANY); // 服务器不bind明确的ip，接收任意ip
            int s = bind(_sockfd, (sockaddr *)&local, sizeof(local));
            if (s == -1)
            {
                cerr << "bind error" << ":" << errno << strerror(errno) << endl;
                exit(BIND_ERR);
            }
        }
        void Start()
        {
            char buffer[gnum];
            for (;;)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
                if (s > 0)
                {
                    buffer[s] = 0;
                    string clientip = inet_ntoa(peer.sin_addr); // 网络到主机 字符串到32位整数
                    uint16_t clientport = ntohs(peer.sin_port);
                    string message = buffer;
                    cout << clientip << "[" << clientport << "]#" << message << endl;
                    // 对读取上来的客户端数据做处理
                    // ...
                    // ...
                    _callback(_sockfd, clientip, clientport, message);
                }
            }
        }
        ~udpServer()
        {
        }

    private:
        uint16_t _port;
        string _ip;
        int _sockfd;
        func_t _callback;
    };
}